package com.jstyle.jclife.activity;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.jstyle.blesdk.cmdenum.SendCmdState;
import com.jstyle.blesdk.constant.DeviceKey;
import com.jstyle.blesdk.model.ExerciseMode;
import com.jstyle.jclife.R;
import com.jstyle.jclife.adapter.YogaAdapter;
import com.jstyle.jclife.ble.BleManager;
import com.jstyle.jclife.utils.DateUtil;
import com.jstyle.jclife.utils.ScreenUtils;
import com.jstyle.jclife.view.TrackStopView;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindArray;
import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import github.hellocsl.layoutmanager.gallery.GalleryLayoutManager;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

public class YogaActivity extends BaseActivity {
    private static final String TAG = "YogaActivity";
    @BindView(R.id.RecyclerView_yoga)
    RecyclerView RecyclerViewYoga;
    Handler handler = new Handler();
    @BindView(R.id.tv_yoga_name)
    TextView tvYogaName;
    @BindView(R.id.iv_yoga_display)
    ImageView ivYogaDisplay;
    @BindView(R.id.bt_yoga_start)
    TrackStopView btYogaStart;
    @BindView(R.id.bt_yoga_cal)
    Button btYogaCal;
    @BindView(R.id.bt_yoga_hr)
    Button btYogaHr;
    Disposable disposableTimer;
    boolean start;
    @BindString(R.string.yoga_cal_laber)
    String yogaCalLabel;
    @BindString(R.string.yoga_hr_laber)
    String yogaHrLabel;
    @BindString(R.string.yoga_time_label)
    String yogaTimeLabel;
    @BindString(R.string.yoga_time_label2)
    String yogaTimeLabel2;
    @BindArray(R.array.yoga_arrays)
    String[] yogaArrays;
    @BindView(R.id.bt_yoga_time)
    Button btYogaTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yoga);
        ButterKnife.bind(this);
        init();
    }

    int mCurrentOffx;
    int selectedPosition;

    private void init() {

        final GalleryLayoutManager manager = new GalleryLayoutManager(GalleryLayoutManager.HORIZONTAL);

        manager.attach(RecyclerViewYoga);
        final YogaAdapter yogaAdapter = new YogaAdapter(ScreenUtils.getScreenWidth(this));
        yogaAdapter.setOnItemClickListener(new YogaAdapter.ItemClickListener() {
            @Override
            public void onItemClick(final int position) {
                RecyclerViewYoga.smoothScrollToPosition(position);
            }
        });

        manager.setOnItemSelectedListener(new GalleryLayoutManager.OnItemSelectedListener() {
            @Override
            public void onItemSelected(RecyclerView recyclerView, View item, final int position) {
                //   selectedPosition=position;
                Log.i(TAG, "onItemSelected: " + position + " " + recyclerView.getScrollState());
                tvYogaName.setText(yogaArrays[position]);

                int id = getResources().getIdentifier("yoga_display_" + position, "drawable", getPackageName());

                ivYogaDisplay.setImageResource(id);


                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        yogaAdapter.setSelected(position);

                    }
                });

            }
        });
        RecyclerViewYoga.setAdapter(yogaAdapter);
        btYogaStart.setOnStopListener(new TrackStopView.onLongClickListener() {
            @Override
            public void finish() {
               YogaActivity.this.finish();
            }

            @Override
            public void onClick() {
//                if (BleManager.getInstance().isConnected()) {
//                    start = !start;
//                    enableMode(start);
//                    btYogaStart.setBitmap(start ? R.drawable.yoga_stop : R.drawable.yoga_start);
//                    if (start) {
//                        startTimer();
//                    } else {
//                        unSubscribe(disposableTimer);
//                        btYogaCal.setText("--");
//                        btYogaHr.setText("--");
//                        btYogaTime.setText("--");
//                        initCal = 0;
//                    }
//
//                }
            }
        });
//        Bitmap bitmap= BitmapFactory.decodeResource(getResources(), R.drawable.yoga_stop);
//
//        btYogaStart.setBitmap(bitmap);
        startTimer();
    }

    private void enableMode(boolean enable) {
        ExerciseMode exerciseMode = new ExerciseMode();
        exerciseMode.setEnableStatus(enable ? ExerciseMode.Status_START : ExerciseMode.Status_FINISH);
        exerciseMode.setExerciseMode(ExerciseMode.Mode_YOGA);
        sendData(SendCmdState.Set_EXERCISE_MODE, exerciseMode);
    }
//    @OnClick(R.id.bt_yoga_start)
//    public void onViewClicked() {
//        Log.i(TAG, "onViewClicked: ");
//
//    }

    public void startTimer() {
        if (disposableTimer != null && !disposableTimer.isDisposed()) return;

        Observable.interval(1, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {
                disposableTimer = d;
            }

            @Override
            public void onNext(Long aLong) {
                long time = aLong;
                String label=aLong>3600?yogaTimeLabel2:yogaTimeLabel;

                btYogaTime.setText(getKcalSpannable(DateUtil.getSportAxieTime((int) time)+label,label));
             //   btYogaStart.
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    float initCal = 0;

    @Override
    public void dataCallback(Map<String, String> maps, SendCmdState sendCmdState) {
        super.dataCallback(maps, sendCmdState);
        switch (sendCmdState) {
            case ACTIVITY_EXERCISE_DATA:
                String heart = maps.get(DeviceKey.KExerciseHeart);
                String cal = maps.get(DeviceKey.KExerciseCal);
                if (Float.valueOf(heart) == 255) return;

                btYogaCal.setText(getKcalSpannable(cal + yogaCalLabel, yogaCalLabel));
                btYogaHr.setText(getKcalSpannable(heart + yogaHrLabel, yogaHrLabel));
                break;
        }
    }

    private Spannable getKcalSpannable(String text, String label) {

        String startText = label;
        int start = text.indexOf(startText);
        int end = start + startText.length();
        Spannable kcalSpannable = new SpannableString(text);
        setSizeSpannable(kcalSpannable, start, end, 15);
        return kcalSpannable;
    }

    private void setSizeSpannable(Spannable word, int start, int end, int textSize) {
        word.setSpan(new AbsoluteSizeSpan(textSize, true), start, end, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        enableMode(false);
        unSubscribe(disposableTimer);
    }
}
